/**
 * Created by fang.ming on 2017/2/24.
 */

import {apiUrl} from "../config/env";

export default {
  install(Vue) {
    Vue.http.interceptors.push(function (request, next) {
      // Set server base url.
      if (request.url.charAt(0) !== '/') {
        request.url += '/';
      }

      request.url = apiUrl + request.url;

      //Set access_token.
      let token = window.sessionStorage.getItem("access_token");
      request.headers.set('Authorization', 'Bearer ' + token);
      next(function (response) {
        // modify response
        // Go to login page if session time out.
        if (response.status === 401) {
          if(response.body.error === 'expired_token' && response.body.error_description.startsWith('access_token')){
            var form = "grant_type=refresh_token&refresh_token=" + window.sessionStorage.getItem("refresh_token") + "&client_id=15efc3a500adbba22852c8792e4ae5a1&client_secret=30e945402c8648fbc93c7eba98fdcc89";
            var headers = {headers: {"content-Type": "application/x-www-form-urlencoded"}};
            Vue.http.post("/oauth2/token", form, headers).then(function (res) {
              window.sessionStorage.setItem("access_token",res.body.access_token);
              window.sessionStorage.setItem("refresh_token",res.body.refresh_token);
            });
          }else if(response.body.error === 'expired_token' && response.body.error_description.startsWith('refresh_token')){
            window.location.href = apiUrl + "/login";
          }
        } else if (response.status === 403) {
          // Vue.message.info('您没有操作权限!请联系管理员!');
        }
        // if(!response.ok) {
        //   console.error(response);
        // } else if(response.body.status != 200) {
        //   response.ok = false;
        //   console.error(response.body);
        // }

        // Make sure to return response.
        return response;
      });

    });
  }
}
